<!--
 * @Descripttion: 附件上传
 * @version: 
 * @Author: mmzhang
 * @Date: 2021-07-20 15:53:49
 * @LastEditTime: 2022-01-04 13:48:26
-->
<template>
  <div class="upload-enclosure">
    <Upload ref="upload" :disabled="disabledFlag" name="multipartFile"
      :show-upload-list="false" :data="api.data" :format="['jpg','jpeg','png']"
      :headers="api.headers" :on-success="handleSuccess" :on-format-error="handleFormatError"
      :before-upload="handleBefore" multiple :action="api.reqUrl">
      <div
        style="width: 100px;height:100px;line-height: 100px;text-align: center;border: 1px dashed #dadada;cursor: pointer;">
        <Icon type="ios-add" :size="30" />
      </div>
    </Upload>
  </div>
</template>
<script>
  import toolMgr from '@/biz/base/tool.js'
  export default {
    name: 'uploadEnclosure',
    props: {
      // 定义图片归类
      type: {
        type: String,
        default: '',
      },
      attachId: {
        type: Number,
        default: null,
      },
      disabledFlag: {
        type: Boolean,
        default: false,
      },
      images: {
        type: Array,
        default: () => []
      },
    },
    data() {
      return {
        api: toolMgr.unloadFile(),
        fileList: [],
        uploadNum: {
          num: null,
          flag: false
        }
      }
    },
    mounted() {
      this.uploadNum.num = this.images.length
      this.uploadNum.flag = this.images.length > 30 ? true : false
    },
    methods: {
      // 导入格式判断
      handleFormatError(file) {
        this.$Message.error('只支持上传jpg,jpeg,png格式的图片！')
      },

      // 导入前
      handleBefore(file) {
        this.fileList = []
        this.$refs.upload.clearFiles()
        this.uploadNum.num += 1
        if (this.uploadNum.num > 30) {
          !this.uploadNum.flag && this.$Message.error('最多上传30张图片')
          this.uploadNum.flag = true
          return false
        } else {
          return new Promise((resolve, reject) => {
            let limitSize = file.size / 1024 / 1024 <= 2 // 2M以上压缩处理
            // 判断图片大小
            if (limitSize) {
              resolve(file)
            } else {
              this.$tool.compressImg(file, 0.8).then((res) => {
                resolve(res)
              })
            }
          })
        }
      },
      // 上传成功
      handleSuccess(res, file, fileList) {
        if (res.code == '200') {
          let params = {
            url: res.data.imageURL,
          }
          this.fileList.push(params)
          if (this.fileList.length == fileList.length) {
            this.uploadNum.flag = false
            this.$emit('onHandleSuccess', this.fileList, this.type, this.attachId)
          }
        } else {
          this.$Message.error('上传出错')
        }
      },
    },
    watch: {
      images(n) {
        this.uploadNum.num = n.length
      }
    }
  }
</script>
<style lang="scss" scoped>
  .upload-enclosure {
    margin-top: 10px;
  }
</style>